from flask import Flask, jsonify, request
from flask_cors import CORS
import random
from datetime import datetime, timedelta

app = Flask(__name__)
CORS(app)  # 解决跨域问题

# 行业数据分类
INDUSTRIES = ['tech', 'finance', 'retail', 'health', 'education',
              'entertainment', 'transport', 'manufacture', 'energy']


# 生成不同类型的图表数据
def generate_line_bar_data(industry=None):
    """生成折线图/柱状图数据"""
    end_date = datetime.now()
    date_list = [(end_date - timedelta(days=i)).strftime('%m-%d') for i in range(6, -1, -1)]

    # 根据行业生成不同趋势的数据
    if industry == 'tech':
        values = [random.randint(60, 80) + i * 3 for i in range(7)]  # 科技行业上升趋势
    elif industry == 'finance':
        values = [80 + random.randint(-10, 10) for _ in range(7)]  # 金融行业平稳
    elif industry == 'retail':
        values = [50 + random.randint(-20, 20) for _ in range(7)]  # 零售行业波动
    elif industry == 'health':
        values = [40 + i * 5 for i in range(7)]  # 医疗行业上升
    else:
        # 默认随机趋势
        trends = {
            '上升': [random.randint(20, 40) + i * 5 for i in range(7)],
            '下降': [random.randint(50, 70) - i * 5 for i in range(7)],
            '波动': [random.randint(30, 70) for _ in range(7)],
            '平稳': [50 + random.randint(-10, 10) for _ in range(7)]
        }
        trend_key = random.choice(list(trends.keys()))
        values = trends[trend_key]

    return {
        'xAxisData': date_list,
        'seriesData': values
    }


def generate_pie_data(industry=None):
    """生成饼图数据"""
    if industry == 'finance':
        categories = ['银行', '保险', '证券', '基金', '其他']
        base = [40, 25, 15, 10, 10]
    elif industry == 'entertainment':
        categories = ['视频平台', '社交媒体', '游戏', '音乐', '直播']
        base = [35, 25, 20, 10, 10]
    elif industry == 'energy':
        categories = ['石油', '天然气', '煤炭', '可再生能源', '核能']
        base = [30, 25, 20, 15, 10]
    else:
        categories = ['A类产品', 'B类产品', 'C类产品', 'D类产品', '其他']
        base = [30, 25, 20, 15, 10]

    # 添加随机波动
    data = []
    for i, cat in enumerate(categories):
        value = max(5, base[i] + random.randint(-5, 5))
        data.append({'value': value, 'name': cat})

    return {
        'pieData': data
    }


def generate_radar_data(industry=None):
    """生成雷达图数据"""
    if industry == 'health':
        indicators = [
            {'name': '服务质量', 'max': 100},
            {'name': '技术水平', 'max': 100},
            {'name': '设施条件', 'max': 100},
            {'name': '效率', 'max': 100},
            {'name': '满意度', 'max': 100}
        ]
        data = [
            random.randint(80, 95),  # 服务质量
            random.randint(75, 90),  # 技术水平
            random.randint(70, 85),  # 设施条件
            random.randint(65, 80),  # 效率
            random.randint(75, 90)  # 满意度
        ]
    elif industry == 'manufacture':
        indicators = [
            {'name': '生产效率', 'max': 100},
            {'name': '产品质量', 'max': 100},
            {'name': '成本控制', 'max': 100},
            {'name': '灵活性', 'max': 100},
            {'name': '安全性', 'max': 100}
        ]
        data = [
            random.randint(70, 90),  # 生产效率
            random.randint(80, 95),  # 产品质量
            random.randint(60, 80),  # 成本控制
            random.randint(65, 85),  # 灵活性
            random.randint(85, 95)  # 安全性
        ]
    else:
        indicators = [
            {'name': '易用性', 'max': 100},
            {'name': '性能', 'max': 100},
            {'name': '扩展性', 'max': 100},
            {'name': '可靠性', 'max': 100},
            {'name': '用户体验', 'max': 100}
        ]
        data = [
            random.randint(70, 100),  # 易用性
            random.randint(60, 90),  # 性能
            random.randint(50, 80),  # 扩展性
            random.randint(70, 95),  # 可靠性
            random.randint(65, 90)  # 用户体验
        ]

    return {
        'radarIndicator': indicators,
        'radarData': data
    }


@app.route('/chart-data', methods=['GET'])
def get_chart_data():
    """返回不同类型的图表数据"""
    chart_type = request.args.get('type', 'line')
    industry = request.args.get('industry')

    if chart_type in ['line', 'bar']:
        data = generate_line_bar_data(industry)
    elif chart_type == 'pie':
        data = generate_pie_data(industry)
    elif chart_type == 'radar':
        data = generate_radar_data(industry)
    else:
        # 默认返回折线图数据
        data = generate_line_bar_data(industry)

    return jsonify(data)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)